package me.lwn.auth.security.web.authentication;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import static me.lwn.auth.security.utils.Constants.*;

@Component
public class RedisSmsVerifyService implements SmsVerifyService {

    private final RedisTemplate<String, Object> redisTemplate;

    public RedisSmsVerifyService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private boolean verifyInvalid(String key, String code) {
        Object cacheCode = redisTemplate.opsForValue().get(key);
        if (cacheCode == null) {
            return false;
        }
        boolean result = !code.equalsIgnoreCase(cacheCode.toString());
        if (!result) {
            redisTemplate.delete(key);
        }
        return result;
    }

    @Override
    public boolean isInvalidLoginCode(String mobile, String code) {
        return verifyInvalid(SPRING_SECURITY_FORM_LOGIN_SMS_CODE_CACHE_KEY + mobile, code);
    }

    @Override
    public boolean isInvalidChangePasswordCode(String mobile, String code) {
        return verifyInvalid(SPRING_SECURITY_CHANGE_PASSWORD_SMS_CODE_CACHE_KEY + mobile, code);
    }

    @Override
    public boolean isInvalidForgetPasswordCode(String mobile, String code) {
        return verifyInvalid(SPRING_SECURITY_FORGET_PASSWORD_SMS_CODE_CACHE_KEY + mobile, code);
    }
}
